package com.naihe.anderson.sms.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.naihe.anderson.sms.R;
import com.naihe.anderson.sms.adapter.NoteAdapter;
import com.naihe.anderson.sms.application.NhSmsApp;
import com.naihe.anderson.sms.constants.NhSmsConstants;
import com.naihe.anderson.sms.entity.Note;
import com.naihe.anderson.sms.listener.OnRecordListener;
import com.naihe.anderson.sms.manager.NoteMgr;
import com.naihe.anderson.sms.widgets.LongClickDialog;
import com.naihe.anderson.sms.widgets.RoundedRectListView;
import com.naihe.anderson.sms.widgets.SystemAlertDialog;

public class NoteActivity extends Activity implements OnClickListener, OnItemClickListener, OnItemLongClickListener,OnRecordListener {
	public static final int REQUEST_UCNOTE_CODE = 12;

	Button create_btn;
	Button back_btn;
	ListView note_list;
	NoteAdapter noteAdapter;

	NhSmsApp nhSmsApp;
	NoteMgr noteMgr;
	List<Note> noteList = new ArrayList<Note>();
	String sdStatus;
	
	RelativeLayout new_layout;
	ImageButton goto_create_btn;
	
	public static final int MSG_WHAT_DATA_CHANGE = 0;
	public static final int MSG_WHAT_MENU_DEL_NOTE = 1;
	Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_WHAT_DATA_CHANGE:
				noteList.clear();
				noteList.addAll(noteMgr.getNoteList());
				noteAdapter.notifyDataSetChanged();
				
				if(noteList.size() == 0){
					new_layout.setVisibility(View.VISIBLE);
				} else {
					if(new_layout.isShown()) new_layout.setVisibility(View.GONE);
				}
				break;
			case MSG_WHAT_MENU_DEL_NOTE:
				Note note = (Note) msg.obj;
				noteMgr.delNote(note);
				break;
			default:
				break;
			}
		}
		
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.note_layout);
		sdStatus = Environment.getExternalStorageState();
		nhSmsApp = (NhSmsApp) getApplication();
		nhSmsApp.setActivity(this);
		noteMgr = nhSmsApp.getNoteMgr();
		noteMgr.setListener(this);
		initView();
		
		mHandler.sendEmptyMessage(MSG_WHAT_DATA_CHANGE);
	}
	

	public void initView() {

		new_layout = (RelativeLayout) findViewById(R.id.new_layout);
		goto_create_btn = (ImageButton) findViewById(R.id.goto_create_btn);
		goto_create_btn.setOnClickListener(this);
		
		note_list = (ListView) findViewById(R.id.note_list);
		noteAdapter = new NoteAdapter(NoteActivity.this, noteList);
		note_list.setAdapter(noteAdapter);
		note_list.setOnItemClickListener(this);
		note_list.setOnItemLongClickListener(this);
		
		create_btn = (Button) findViewById(R.id.create_btn);
		create_btn.setOnClickListener(this);

		back_btn = (Button) findViewById(R.id.back_btn);
		back_btn.setOnClickListener(this);
	}

	private static final String WENZI = "文字便签";
	private static final String TUPIAN = "图片便签";
	
	PopupWindow checkPWindow = null;
	private void initCheckPWindow(){
		String[] muenString = new String[]{WENZI,TUPIAN};
		LayoutInflater mLayoutInflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);  
        View popunwindwow = mLayoutInflater.inflate( R.layout.menu_popup, null);
        RoundedRectListView menuListView = (RoundedRectListView) popunwindwow.findViewById(R.id.menuListView);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(NoteActivity.this, R.layout.simple_list_item, muenString);
        menuListView.setAdapter(adapter);
        menuListView.setOnItemClickListener(this);
        
        checkPWindow = new PopupWindow(popunwindwow, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); 
        checkPWindow.setBackgroundDrawable(new BitmapDrawable());//点击窗口外消失  
        checkPWindow.setOutsideTouchable(true);  
        checkPWindow.setFocusable(true);
	}
	
	private void toFinishActivity(){
		nhSmsApp.setActivity(null);
		noteMgr.setListener(null);
		finish();
		System.gc();
	}
	
	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.create_btn || v.getId() == R.id.goto_create_btn) {
			if(checkPWindow == null)
				initCheckPWindow();
			checkPWindow.update();
			checkPWindow.showAsDropDown(create_btn);
		} else if (v.getId() == R.id.back_btn) {
			toFinishActivity();
		} else if(v.getId() == R.id.checkbtn_cancel){
			mPopupWindow.dismiss();
			mPopupWindow = null;
		} else if(v.getId() == R.id.checkbtn_ok){
			Note note = (Note) v.getTag();
			String signature = editText.getText().toString().trim();
			if(!TextUtils.isEmpty(note.cipher)){//解除
				if(note.cipher.equals(signature)){
					//success
					noteMgr.setNotePasswd(note, "");
					mPopupWindow.dismiss();
					mPopupWindow = null;
					Toast.makeText(NoteActivity.this, getResources().getString(R.string.mima_jiechu_success), Toast.LENGTH_SHORT).show();
				} else {
					editText.setText("");
					Toast.makeText(NoteActivity.this, getResources().getString(R.string.mima_error), Toast.LENGTH_SHORT).show();
				}
	        } else {
	        	noteMgr.setNotePasswd(note, signature);
	        	mPopupWindow.dismiss();
	        	mPopupWindow = null;
	        	Toast.makeText(NoteActivity.this, getResources().getString(R.string.mima_set_success), Toast.LENGTH_SHORT).show();
	        }
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 截获按键事件
		if (KeyEvent.KEYCODE_BACK == keyCode) {
			toFinishActivity();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(data == null || data.getExtras() == null)
			return;
		if (requestCode == REQUEST_UCNOTE_CODE && resultCode == RESULT_OK) {
			String type = data.getStringExtra("type");
			Note note = (Note) data.getSerializableExtra("note");
			if(type.equals("create")){
				noteMgr.insert(note);
			} else if(type.equals("update")){
				noteMgr.update(note);
			} else {
				
			}
		}
	}


	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if(parent.getAdapter().getClass().equals(NoteAdapter.class)){
			Note note = noteAdapter.getItem(position);
			if(note == null) return;
			
			intentToActivity(note.picpath, note);
		} else {
			@SuppressWarnings("unchecked")
			String opter = ((ArrayAdapter<String>)parent.getAdapter()).getItem(position);
			intentToActivity(opter, null);
			checkPWindow.dismiss();
		}
	}

	private void intentToActivity(String opter, Note note){
		if(TextUtils.isEmpty(opter))
			opter = WENZI;
		
		if(opter.equals(WENZI)){
			Intent intent = new Intent(NoteActivity.this, NoteCreateActivity.class);
			if(note != null) intent.putExtra("note", note);
			startActivityForResult(intent, REQUEST_UCNOTE_CODE);
		} else if(opter.equals(TUPIAN) || opter.startsWith(NhSmsConstants.PICNOTE_PREFIX) || opter.startsWith(NhSmsConstants.MONRY_PREFIX)){
			if (sdStatus.equals(Environment.MEDIA_MOUNTED)) {
				Intent intent = new Intent(NoteActivity.this, PicNoteCreateActivity.class);
				if(note != null) intent.putExtra("note", note);
				startActivityForResult(intent, REQUEST_UCNOTE_CODE);
			} else {
				Toast.makeText(NoteActivity.this, R.string.sderror, Toast.LENGTH_SHORT).show();
			}
		}
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		final Note note = noteAdapter.getItem(position);
		if(note == null) return false;
		
		String noteMima = TextUtils.isEmpty(note.cipher) ? getResources().getString(R.string.note_add_mima) : getResources().getString(R.string.note_remove_mima);
		String[] links = new String[]{noteMima, getResources().getString(R.string.note_del_menu)};
		new LongClickDialog(NoteActivity.this, links, getResources().getString(R.string.operation), new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if(position == ITEM_LONG_CLICK_NOTE_ADD_MIMA){
					initPopupWindows(note);
					
					mPopupWindow.update();
					mPopupWindow.showAtLocation(findViewById(R.id.makenew_topLayOut), Gravity.CENTER, 0, 0);
				} else if(position == ITEM_LONG_CLICK_NOTE_DEL_MENU){
					if(!TextUtils.isEmpty(note.cipher)){
						Toast.makeText(NoteActivity.this, getResources().getString(R.string.menu_popup_has_password), Toast.LENGTH_SHORT).show();
						return;
					}
					
					Message message = mHandler.obtainMessage();
					message.what = MSG_WHAT_MENU_DEL_NOTE;
					message.obj = note;
					
					new SystemAlertDialog(NoteActivity.this, mHandler, 
							getResources().getString(R.string.menu_btn_text_menu_bottom), 
							getResources().getString(R.string.alert_del_note), 
							getResources().getString(R.string.cancel), 
							getResources().getString(R.string.ok), message).show();
				}
			}
		}).show();
		return false;
	}
	
	PopupWindow mPopupWindow = null;
	EditText editText;
	private void initPopupWindows(Note note){
		LayoutInflater mLayoutInflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);  
        View popunwindwow = mLayoutInflater.inflate( R.layout.popup_edit_layout, null);
        editText = (EditText) popunwindwow.findViewById(R.id.baseSignature_edit);
        Button checkbtn_cancel =(Button) popunwindwow.findViewById(R.id.checkbtn_cancel);
        Button checkbtn_ok =(Button) popunwindwow.findViewById(R.id.checkbtn_ok);
        TextView title_text = (TextView) popunwindwow.findViewById(R.id.title_text);
       
        editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        editText.setHint(getResources().getString(R.string.save_key_word));
        if(!TextUtils.isEmpty(note.cipher)){
        	title_text.setText(getResources().getString(R.string.note_remove_mima));
        	checkbtn_ok.setText(getResources().getString(R.string.mima_btn_jiechu));
        } else {
        	title_text.setText(getResources().getString(R.string.note_add_mima));
        }
        checkbtn_cancel.setOnClickListener(NoteActivity.this);
        checkbtn_ok.setOnClickListener(NoteActivity.this);
        checkbtn_ok.setTag(note);
        
        mPopupWindow = new PopupWindow(popunwindwow, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); 
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());//点击窗口外消失  
        mPopupWindow.setOutsideTouchable(true);  
        mPopupWindow.setFocusable(true);
	}
	
	private static int ITEM_LONG_CLICK_NOTE_ADD_MIMA = 0;
	private static int ITEM_LONG_CLICK_NOTE_DEL_MENU = 1;

	@Override
	public void onDataChanged() {
		mHandler.sendEmptyMessage(MSG_WHAT_DATA_CHANGE);
	}
}
